#!/usr/bin/env python3
"""
BoLe HR Platform - 系统启动脚本
一键启动前后端服务
"""

import os
import sys
import subprocess
import time
import signal
import threading
from pathlib import Path

class SystemManager:
    def __init__(self):
        self.backend_process = None
        self.frontend_process = None
        self.running = True
        
    def start_backend(self):
        """启动后端服务"""
        print("🚀 启动JH AI聊天服务...")
        print("⚠️ 注意：暂时使用独立的JH服务器（跳过lightrag功能）")
        try:
            # 在Windows上设置正确的编码环境
            env = os.environ.copy()
            if sys.platform == "win32":
                env['PYTHONIOENCODING'] = 'utf-8'
                env['PYTHONLEGACYWINDOWSSTDIO'] = '1'
            
            self.backend_process = subprocess.Popen([
                sys.executable, "simple_jh_server.py"
            ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, 
            encoding='utf-8', errors='replace', env=env)
            
            # 等待后端启动
            time.sleep(3)
            
            if self.backend_process.poll() is None:
                print("✅ JH AI聊天服务启动成功 - http://localhost:8000")
                return True
            else:
                stdout, stderr = self.backend_process.communicate()
                print(f"❌ 后端服务启动失败: {stderr}")
                return False
                
        except Exception as e:
            print(f"❌ 后端服务启动异常: {e}")
            return False
    
    def start_frontend(self):
        """启动前端服务"""
        print("🌐 启动前端Web服务...")
        try:
            frontend_path = Path("frontend")
            if not frontend_path.exists():
                print(f"❌ 前端目录不存在: {frontend_path}")
                return False
            
            # 在Windows上设置正确的编码环境
            env = os.environ.copy()
            if sys.platform == "win32":
                env['PYTHONIOENCODING'] = 'utf-8'
                env['PYTHONLEGACYWINDOWSSTDIO'] = '1'
            
            self.frontend_process = subprocess.Popen([
                sys.executable, "server.py", "3000"
            ], cwd=frontend_path, stdout=subprocess.PIPE, 
            stderr=subprocess.PIPE, encoding='utf-8', errors='replace', env=env)
            
            # 等待前端启动
            time.sleep(2)
            
            if self.frontend_process.poll() is None:
                print("✅ 前端Web服务启动成功 - http://localhost:3000")
                return True
            else:
                stdout, stderr = self.frontend_process.communicate()
                print(f"❌ 前端服务启动失败: {stderr}")
                return False
                
        except Exception as e:
            print(f"❌ 前端服务启动异常: {e}")
            return False
    
    def monitor_services(self):
        """监控服务状态"""
        while self.running:
            try:
                # 检查后端服务
                if self.backend_process and self.backend_process.poll() is not None:
                    print("⚠️ 后端服务意外停止，尝试重启...")
                    self.start_backend()
                
                # 检查前端服务
                if self.frontend_process and self.frontend_process.poll() is not None:
                    print("⚠️ 前端服务意外停止，尝试重启...")
                    self.start_frontend()
                
                time.sleep(5)  # 每5秒检查一次
                
            except Exception as e:
                print(f"❌ 服务监控异常: {e}")
                time.sleep(5)
    
    def stop_services(self):
        """停止所有服务"""
        print("🛑 正在停止服务...")
        self.running = False
        
        if self.backend_process:
            try:
                self.backend_process.terminate()
                self.backend_process.wait(timeout=5)
                print("✅ 后端服务已停止")
            except Exception as e:
                print(f"⚠️ 强制停止后端服务: {e}")
                self.backend_process.kill()
        
        if self.frontend_process:
            try:
                self.frontend_process.terminate()
                self.frontend_process.wait(timeout=5)
                print("✅ 前端服务已停止")
            except Exception as e:
                print(f"⚠️ 强制停止前端服务: {e}")
                self.frontend_process.kill()
    
    def handle_signal(self, signum, frame):
        """处理系统信号"""
        print(f"\n📨 收到信号 {signum}，正在优雅退出...")
        self.stop_services()
        sys.exit(0)

def main():
    """主函数"""
    print("=" * 60)
    print("🎯 BoLe HR Platform - 智能招聘系统")
    print("🔧 集成JH子系统 - 求职者职位分析平台")
    print("=" * 60)
    
    # 创建系统管理器
    manager = SystemManager()
    
    # 注册信号处理器
    signal.signal(signal.SIGINT, manager.handle_signal)
    signal.signal(signal.SIGTERM, manager.handle_signal)
    
    try:
        # 启动后端服务
        if not manager.start_backend():
            print("❌ 后端服务启动失败，退出")
            return
        
        # 启动前端服务
        if not manager.start_frontend():
            print("❌ 前端服务启动失败，但后端服务仍在运行")
            print("📋 您可以手动访问后端API: http://localhost:8000/docs")
        
        print("\n" + "=" * 60)
        print("🎉 系统启动完成!")
        print("📱 前端界面: http://localhost:3000")
        print("🔧 后端API: http://localhost:8000")
        print("📚 API文档: http://localhost:8000/docs")
        print("🤖 JH仪表板: http://localhost:3000/jh_subsystem/jh_dashboard.html")
        print("=" * 60)
        print("💡 按 Ctrl+C 停止服务")
        print("=" * 60)
        
        # 启动服务监控
        monitor_thread = threading.Thread(target=manager.monitor_services, daemon=True)
        monitor_thread.start()
        
        # 主线程等待
        while manager.running:
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n📨 收到中断信号，正在停止服务...")
        manager.stop_services()
    except Exception as e:
        print(f"❌ 系统运行异常: {e}")
        manager.stop_services()
    finally:
        print("👋 感谢使用 BoLe HR Platform!")

if __name__ == "__main__":
    main()